package com.wmz.controller;

import cn.hutool.core.date.DateUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.wmz.config.AliyunOSSConfig;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.net.URL;
import java.util.Date;

/**
 * @author wmz
 * @date 2024/7/19 23:07
 * @description 文件上传控制层
 */
@Api(tags = "文件上传接口管理")
@RestController
@Slf4j
@RequestMapping("admin/file")
public class FileUploadController {
    @Autowired
    private AliyunOSSConfig aliyunOSSConfig;

    /**
     * 上传单个文件
     * 1. 接口必须是post请求
     * 2. 接收对象类型：MultipartFile 该对象是你SpringMVC提供的
     * @param file
     * @return
     */
    @ApiOperation("上传单个文件")
    @PostMapping("upload/element")
    public String uploadFile(MultipartFile file) {
        // 填写Bucket名称
        String bucketName = aliyunOSSConfig.getBucketName();
        // 以天为的单位的名称作为文件夹名称
        String newFolderName = DateUtil.format(new Date(), "yyyy-mm-dd");
        // 创建完整路径：以时间戳作为文件名
        String newFileName = DateUtil.format(new Date(), "HHmmssSSS");
        //获取原文件名称
        String fileSuffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        String objectName = newFolderName + "/" + newFileName + fileSuffix;

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(aliyunOSSConfig.getEndpoint(),aliyunOSSConfig.getAccessKeyId(),aliyunOSSConfig.getAccessKeySecret());
        URL url = null;
        try {
            // 创建PutObjectRequest对象
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, file.getInputStream());
            // 上传字符串。
            ossClient.putObject(putObjectRequest);
            //创建上传文件访问的url地址
             url = ossClient.generatePresignedUrl(bucketName, objectName, DateUtil.offsetDay(new Date(), 365 * 10));
        } catch (Exception ce) {
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return url.toString();
    }
}
